<template>
<Row :gutter="16">
    <Col span="8">
        <Input v-model="model.full_name" readonly>
            <Select v-model="selected_method" style="width:100px" slot="prepend">
                <Option v-for="item in method_list" :value="item" :key="item">{{ item }}</Option>
            </Select>
            <Button type="primary" slot="append" @click="handleSend" :loading="is_loading">发送</Button>
        </Input>
        <Input v-for="(item, key) in args" :key="key" v-model="args[key]" :placeholder="model.args[key].example.toString()" style="margin-top:5px;">
            <Button type="ghost" slot="prepend" style="width:100px">{{key}}</Button>
        </Input>
        <div id="request_json" class="ivu-description" style="margin-top:16px"></div>
    </Col>
    <Col span="16">
        <div id="result_json" class="ivu-description"></div>
    </Col>
</Row>
</template>

<script>
export default {
    name: "Simulation",
    props: {
        model: Object
    },
    data() {
        return {
            selected_method: "post",
            method_list: ["get", "post"],
            args: {},
            result: {},
            is_loading: false
        };
    },
    computed: {

    },
    methods: {
        handleSend() {
            this.renderRequestJson();
            var config = {
                url: this.model.full_name,
                method: this.selected_method,
                baseURL: ""
            };
            if(this.selected_method == "get") {
                config.params = this.args;
            }else {
                config.data = this.args;
            }
            this.is_loading = true;
            this.result = {};
            this.renderResultJson();
            this.ajax(config).then( res => {
                this.is_loading = false;
                this.result = res.data;
                this.renderResultJson();
            }).catch( error => {
                this.is_loading = false;
                this.result = { message: error.toString() };
                this.renderResultJson();
            });
        },
        copyArgs(value) {
            var temp = {};
            for(var key in value.args) {
                temp[key] = value.args[key].default
            }
            this.args = temp;
            this.renderRequestJson();
        },
        renderRequestJson() {
            $("#request_json").JSONView(this.args, { collapsed: false });
        },
        renderResultJson() {
            $("#result_json").JSONView(this.result, { collapsed: false });
        }
    },
    watch: {
        "model": "copyArgs"
    }
}
</script>